var regModule = angular.module("reg", ['Service']);

/* TODO password watch 
 * cancel the red after repass get corrected
 */
regModule.controller('RegController', function($scope,$http){
	$scope.passDiff = true;
	// useful methods 
	$scope.util = {
		// check if the two passwords are same
		passIsSame : function(){
			return $scope.password.value == $scope.repassword.value ?
				true : false;
		},
		// add "red" if two password are not same
		passDiff : function(){
			document.getElementById("repassword-group").classList.add("has-error");;
			$scope.repassword.value = "";
			document.querySelector("#repassword-group label").innerHTML = "两次输入密码不一致";
			document.getElementById("repassword").focus();
		},
		// remove "has-error" style
		passSame : function(){
			document.getElementById("repassword").classList.remove("has-error");
		},
		// add "red"
		mailToken : function(){
			document.getElementById("email-group").classList.add("has-error");	
			$scope.email.value = "";
			document.querySelector("#email-group label").innerHTML = "邮箱已经被占用";
			document.getElementById("email").focus();
		},
		// remove all "red"
		resetRed : function(){
			document.getElementById("email-group").classList.remove("has-error");
			document.getElementById("repassword-group").classList.remove("has-error");
		}
	};

	$scope.submitbtn = "确认注册";	
	$scope.submit = function(){
		$scope.util.resetRed();
		// confirm the password
		if(!$scope.util.passIsSame()){
			$scope.util.passDiff();
			return;
		} 
		// data to be sent
		var data = {
			email:$scope.email.value,
			name: $scope.name.value,
			password: $scope.password.value
		};
		$http.post('/user',data).success(function(data){
			if(data.suc == true){
				document.getElementById('sbm').classList.add('btn-success');	
				$scope.submitbtn = "注册成功";
				// TODO 此处应(引导)跳转到用户之前打算访问的页面
			}else{
				if(data.because == "email-used"){
					$scope.util.mailToken();	
				}
			}
		});	
	};
});
